package com.nb.controller.admin;


import com.nb.result.Result;
import com.nb.service.AdminService;
import com.nb.vo.admin.*;
import com.nb.vo.admin.BodyOV.AdminHostitalUpdate;
import com.nb.vo.admin.BodyOV.AdminSettingUpdateCost;
import com.nb.vo.admin.BodyOV.AdminUsersAdd;
import com.nb.vo.admin.BodyOV.AdminUsersUpdate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 获取备份记录接口
     */
    @GetMapping("/data/backupRecords")
    public Result getBackupRecords() {
        try {
            List<BackupRecordVO> records = adminService.getBackupRecords();
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取备份记录失败: ", e);
            return Result.error("获取备份记录失败：" + e.getMessage());
        }
    }

    @GetMapping("/users")
    public Result getDoctorInfo(HttpServletRequest request) {

        List<AdminGetUsers> list = adminService.getAllUsers();

        return list == null ? Result.error("非管理员无权查找！") : Result.success(list);
    }

    @PatchMapping("users/update")
    public Result usersUpdate(@RequestBody AdminUsersUpdate ov) {

        return adminService.updateUser(ov) ? Result.success() : Result.error("更新失败");
    }

    @DeleteMapping("/users/delete")
    public Result deleteUser(@RequestParam String id) {

        return adminService.deleteUser(id) ? Result.success() : Result.error("删除失败");
    }

    @PostMapping("/users/add")
    public Result adminUsersAdd(@RequestBody AdminUsersAdd ov) {

        return adminService.addUser(ov) ? Result.success() : Result.error("添加新用户失败");
    }

    @PatchMapping("/permissions/addAdmin")
    public Result updateAddAdmin(@RequestParam String id) {

        return adminService.updateAddAdmin(id) ? Result.success() : Result.error("设置管理员失败");
    }

    @PatchMapping("/permissions/deleteAdmin")
    public Result updateDeleteAdmin(@RequestParam String id) {

        return adminService.updateDeleteAdmin(id) ? Result.success() : Result.error("设置移除管理员失败");
    }

    @GetMapping("/setting/base")
    public Result getHospitalInfo(HttpServletRequest request) {

        AdminSettingBase list = adminService.getHospitalInfo();

        return list == null ? Result.error("医院返回失败") : Result.success(list);
    }

    /**
     * 数据恢复接口
     */
    @PostMapping("/data/restore")
    public Result restoreData(@RequestParam("file") MultipartFile file) {
        try {
            boolean result = adminService.restoreData(file);
            return result ? Result.success("数据恢复成功") : Result.error("数据恢复失败");
        } catch (Exception e) {
            log.error("数据恢复失败: ", e);
            return Result.error("数据恢复失败：" + e.getMessage());
        }
    }

    @PutMapping("/setting/updateBase")
    public Result updateHospital(@RequestBody AdminHostitalUpdate ov) {

        return adminService.updateHospitalInfo(ov) ? Result.success() : Result.error("医院信息更新失败");
    }

    @GetMapping("/setting/cost")
    public Result getSettingCost(HttpServletRequest request) {

        List<AdminSettingCost> list = adminService.getSettingCost();

        return Result.success(list);
    }

    @PutMapping("/setting/updateCost")
    public Result settingCost(@RequestBody List<AdminSettingUpdateCost> ov) {

        return adminService.updateSettingCost(ov) ? Result.success() : Result.error("更新挂号费失败！");
    }

    @GetMapping("/setting/structure")
    public Result settingStructure(HttpServletRequest request) {

        List<AdminSettingStructure> list = adminService.getSettingStructure();

        return Result.success(list);
    }

    @GetMapping("/setting/consultation")
    public Result settingConsultation(HttpServletRequest request) {

        TwoArrReturn list = adminService.getSettingConsultation();

        return Result.success(list);
    }

    @GetMapping("/setting/appointment")
    public Result settingAppointment(HttpServletRequest request) {

        TwoArrReturn list = adminService.getSettingAppointment();

        return Result.success(list);
    }

    @GetMapping("/permissions")
    public Result getPermissions(HttpServletRequest request) {

        List<AdminPermissions> list = adminService.getPermissions();

        return Result.success(list);
    }

    /**
     * 数据备份接口
     */
    @GetMapping("/data/backup")
    public ResponseEntity<byte[]> backupData() {
        try {
            String backupPath = adminService.backupData();
            Path path = Paths.get(backupPath);
            byte[] data = Files.readAllBytes(path);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "data_backup.sql");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
        } catch (Exception e) {
            log.error("数据备份失败: ", e);
            return ResponseEntity.notFound().build();
        }
    }

//    @GetMapping("/data/backup")
//    public Result backupData() {
//        try {
//            String backupPath = adminService.backupData();
//            return Result.success("数据备份成功", backupPath);
//        } catch (Exception e) {
//            log.error("数据备份失败: ", e);
//            return Result.error("数据备份失败：" + e.getMessage());
//        }
//    }

    /**
     * 下载备份记录文件接口
     */
    @GetMapping("/data/downloadBackup/{id}")
    public ResponseEntity<byte[]> downloadBackup(@PathVariable("id") Integer id) {
        try {
            byte[] data = adminService.downloadBackup(id);
            
            // 获取备份记录列表
            List<BackupRecordVO> records = adminService.getBackupRecords();
            
            // 查找对应ID的记录
            String fileName = "backup.sql";
            for (BackupRecordVO record : records) {
                if (record.getId().equals(id)) {
                    fileName = record.getName();
                    break;
                }
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
        } catch (Exception e) {
            log.error("下载备份文件失败: ", e);
            return ResponseEntity.notFound().build();
        }
    }
}
